﻿using System;
using System.Activities;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace TCM.Controllers
{
    public class CourseController : Controller
    {
        #region Common Variables
        private TCMContext db = new TCMContext();
        #endregion

        #region construction methods
        public CourseController()
        {
            ViewBag.SelectDayOfWeek = this.SelectListDayOfWeek;
            ViewBag.SelectListInstructors = this.SelectListInstructors;
            ViewBag.SelectListRooms = this.SelectListRooms;
            //ViewBag.SelectListRquiredExam = this.SelectListRquiredExam;
            ViewBag.SelectedListSubjects = this.SelectedListSubjects;
            ViewBag.SelectListLevels = this.ListLevel;
        }
        #endregion

        #region Course methods

        //
        // GET: /Course/
        public ActionResult Index()
        {
            var Courses = db.Courses.Include(c => c.Instructor).Include(c => c.Level);

            return View(Courses.ToList());
        }

        //
        // GET: /Course/Details/5
        public ActionResult Details(Guid? id = null)
        {
            Course Course = db.Courses.Find(id);
            if (Course == null)
            {
                return HttpNotFound();
            }
            return View(Course);
        }

        //
        // GET: /Course/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Course/Create
        [HttpPost]
        public ActionResult Create(Course Course)
        {
            if (ModelState.IsValid)
            {
                Course.CourseID = Guid.NewGuid();
                var svData = db.Courses.Add(Course);
                db.SaveChanges();
                //return RedirectToAction("Index");
                return RedirectToAction("edit/" + svData.CourseID.ToString());
            }


            return View(Course);
        }

        //
        // GET: /Course/Edit/5
        public ActionResult Edit(Guid? id = null)
        {
            if (!id.HasValue)
            {
                return View();
            }
            Course course = db.Courses
                .Include(p => p.Agenda)
                .Include(p => p.CourseSchedules)
                .Include(p => p.StudentCourses)
                .Where<Course>(x => x.CourseID.Equals(id.Value))
                .FirstOrDefault();
            
            
            if (course == null)
            {
                return HttpNotFound();
            }
            course.students = course.StudentCourses.Select(p => p.StudentID).AsEnumerable();

           

           // ViewBag.SelectListRquiredExam = this.SelectListRquiredExam;

            foreach (var SchdeduleLine in course.CourseSchedules)
            {
                if (SchdeduleLine.DayID.HasValue)
                {
                    var DayName = this.SelectListDayOfWeek
                        .Where(x => x.Value == SchdeduleLine.DayID.Value.ToString())
                        .FirstOrDefault();
                    SchdeduleLine.DayName = DayName.Text;
                }
            }

            return View(course);
        }

        public ActionResult GenerateScheduleCourse(Guid? id = null)
        {
            var Course = db.Courses.Find(id);
            InOutArgument<Course> ff = new InOutArgument<Course>();
            foreach (var item in Course.CourseSchedules)
            {
                var day = db.WeekDays.Find(item.DayID);

                item.DayName = day.DayName;
            }

            var input = new Dictionary<string, object> { { "eEntity", Course } };


           // WorkflowInvoker.Invoke(new Workflows.AgendaOnCreating(), input);

            db.SaveChanges();
            return RedirectToAction("edit/" + id.ToString());
        }

        //
        // POST: /Course/Edit/5
        [HttpPost]
        public ActionResult Edit(Course course)
        {


            #region Update Status
            //#region Schedule
            var UpdateSchedules = course.CourseSchedules.Where(p=>db.CourseSchedules.Select(s=>s.CourseScheduleID).Contains(p.CourseScheduleID));
            foreach (var UpdateSchedule in UpdateSchedules)
            {
                db.Entry(UpdateSchedule).State = EntityState.Modified;
            }
            #endregion

            //#region Agenda
            //var UpdateAgendas = from x in Course.Agenda
            //                    where x.DeleteByUI == false
            //                          && x.AgendaID != Guid.Empty
            //                    select x;
            //foreach (var UpdateAgenda in UpdateAgendas)
            //{
            //    db.Entry(UpdateAgenda).State = EntityState.Modified;
            //}
            //#endregion

            #endregion

            #region New status

            #region Schedule
           
            var NewSchedules = course.CourseSchedules.Where(p=>!db.CourseSchedules.Select(s=>s.CourseScheduleID).Contains(p.CourseScheduleID));  
            foreach (var NewSchedule in NewSchedules)
            {
                NewSchedule.CourseScheduleID = Guid.NewGuid();
                NewSchedule.CourseID = course.CourseID;
                db.Entry(NewSchedule).State = EntityState.Added;

            }
            #endregion


            #region student

            IEnumerable<Guid> NewStudentes = course.students.Where(p =>!db.StudentCourses.Where(pp=>pp.CourseID==course.CourseID).Select(s => s.StudentID).Contains(p));
            foreach (var NewStudent in NewStudentes)
            {

                db.StudentCourses.Add(new StudentCourse() { CourseID = course.CourseID, StudentID = NewStudent });

            }
            #endregion
            //#region Agenda
            //var NewAgendas = from x in Course.Agenda
            //                 where x.AgendaID.Equals(Guid.Empty)
            //                 select x;
            //foreach (var NewAgenda in NewAgendas)
            //{
            //    NewAgenda.AgendaID = Guid.NewGuid();
            //    NewAgenda.CourseID = Course.CourseID;
            //    db.Entry(NewAgenda).State = EntityState.Added;
            //}
            //#endregion

            #endregion





            #region Delete Status
            #region avoid the error with delete
            int DeleteAgendaCount = course.Agenda.Where<Agenda>(x => x.DeleteByUI == true).Count();
            int DeleteScheduleAcount = course.CourseSchedules.Where<CourseSchedule>(x => x.DeletedByUI == true).Count();
            if ((DeleteAgendaCount + DeleteScheduleAcount) > 0)
            {
                db.Courses.Attach(course);
            }
            #endregion
            #region schedule

            var DeleteScheduleIDs = (from x in course.CourseSchedules
                                     where x.DeletedByUI == true
                                     select x.CourseScheduleID).ToList();
            foreach (var DeleteScheduleID in DeleteScheduleIDs)
            {
                var ScheduleDeleted = course
                    .CourseSchedules
                    .Where<CourseSchedule>(x => x.DeletedByUI == true)
                    .FirstOrDefault();
                db.CourseSchedules.Attach(ScheduleDeleted);
                db.Entry(ScheduleDeleted).State = EntityState.Deleted;
            }

            #endregion
            #region agenda
            var DeleteAgendaIDs = (from x in course.Agenda
                                   where x.DeleteByUI == true
                                   select x.AgendaID).ToList();
            foreach (var DeleteAgendaID in DeleteAgendaIDs)
            {
                var AgendaDeleted = course
                    .Agenda
                    .Where<Agenda>(p => p.AgendaID.Equals(DeleteAgendaID)).FirstOrDefault();
                db.Agenda.Attach(AgendaDeleted);
                db.Entry(AgendaDeleted).State = EntityState.Deleted;

            }
            #endregion
            #endregion


            db.Entry(course).State = EntityState.Modified;

            //save data to database
            db.SaveChanges();


            //return View(Course); 
            return RedirectToAction("edit/" + course.CourseID.ToString());

        }

        //
        // GET: /Course/Delete/5
        public ActionResult Delete(Guid? id = null)
        {
            Course Course = db.Courses.Find(id);
            if (Course == null)
            {
                return HttpNotFound();
            }
            return View(Course);
        }

        //
        // POST: /Course/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(Guid id)
        {
            Course Course = db.Courses.Find(id);
            db.Courses.Remove(Course);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        //#endregion

        #region Method Partial

        public ActionResult EditRelatedCourseSchedule(string courseid5)

        {
            ViewBag.SelectDayOfWeek = new SelectList(db.WeekDays.ToList(), "DayID", "DayName");
            ///Guid g = db.Courses.Where(r => r.CourseID == CourseID).First().CourseID;
            var s = new CourseSchedule() { CourseID = new Guid(courseid5) ,CourseScheduleID=Guid.NewGuid() };

            return PartialView("EditRelatedCourseSchedule", s);
        }
        public ActionResult _NewRelatedAgenda()
        {
            return PartialView("_RelatedAgenda");
        }
        

        #endregion

        #region helper methods and properties
         
        /// <summary>
        /// this set the 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RemoveSchedule(Guid? id = null)
        {
            if (id.HasValue)
            {
                //System.Diagnostics.Debugger.Break();
                var deleteinstance = db.CourseSchedules.Find(id.Value);
                deleteinstance.DeletedByUI = true;
                if (TryUpdateModel(deleteinstance))
                {                    
                    return View(deleteinstance);
                }
                //db.CourseSchedules.Remove(deleteinstance);
                //db.SaveChanges();
            }
            return null;
            //return "dsds";// Json(new { success = true });
        }

        [ActionName(name:"deleteme")]
        public ActionResult deleteme(Guid?id=null)
        {

            CourseSchedule c = db.CourseSchedules.Find(id);
            Guid courseid = c.CourseID.Value;
            db.CourseSchedules.Remove(c);
            //db.SaveChanges();
            var t = db.CourseSchedules
                .Where<CourseSchedule>(x => x.CourseID.Value.Equals(courseid))
                .AsEnumerable<CourseSchedule>();
           return PartialView("EditRelatedCourseSchedule");
            
        }

       
        /// <summary>
        /// Select DayOfWeek
        /// </summary>
        public SelectList SelectListDayOfWeek
        {
            get
            {
                return new SelectList(db.WeekDays.ToList(), "DayID", "DayName");
            }
        }

        public SelectList SelectListInstructors
        {
            get
            {
                return new SelectList(db.Instructors, "InstructorID", "NAME");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public SelectList SelectListRooms
        {
            get
            {
                return new SelectList(db.Rooms, "RoomID", "Name");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        //public SelectList SelectListRquiredExam
        //{
        //    get
        //    {
        //        var dbRequiredExam = db.c
        //                             .Where<MAPSTRINGBASE>
        //                             (x => x.ATTRIBUTENAME.ToLower().Equals("ExamRequired".ToLower()) &&
        //                                 x.ENTITYNAME.ToLower().Equals("course".ToLower())).ToList();

        //        return new SelectList(dbRequiredExam, "MAPSTRINGID", "DISPLAYNAME");
        //    }
        //}

        public SelectList SelectedListSubjects
        {
            get
            {
                return new SelectList(db.Subjects, "SubjectID", "NAME");
            }
        }
        public SelectList ListLevel
        {
            get
            {
                return new SelectList(db.Levels, "levelid", "NAME");
            }
        }
        

        public string RelatedSelectListSubject(Guid? id = null)
        {
            if (!id.HasValue) return string.Empty;

            //var dbSubjectLevels = null;
            //(from xSubjectlevel in db.SUBJECTLevels
            //                       where xSubjectlevel.SubjectID.Value.Equals(id.Value)
            //                       select new { Value = xSubjectlevel.SUBJECTLEVELID, Text = xSubjectlevel.Name }
            //                       ).ToArray();


            return "";///new JavaScriptSerializer().Serialize(dbSubjectLevels);
            // return null;
        }

        //public SelectList LoadTimeAMPM
        //{
        //    get
        //    {
        //        return null;
        //    }
        //}
        #endregion

    }
}